package com.example.springboot.ytest.geek;

import java.nio.file.Files;
import java.nio.file.Paths;

/**
* test load Hello.xlass
* @author luffy
* @date 2021/3/21 23:25
**/
public class YClassLoader extends ClassLoader {
    public static void main(String[] args){
        try {
            new YClassLoader().findClass("Hello").newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected Class<?> findClass(String name) {
        byte[] bytes = this.makeBytes();
        System.out.println("findClass in");
        Class<?> aClass = defineClass(name, bytes, 0, bytes.length);
        if (null != aClass) {
            System.out.println("findClass out: " + aClass.getName());
            try {
                aClass.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("findClass out: null");
        }
        return aClass;
    }

    private byte[] makeBytes() {
        try {
            byte[] bytes = Files.readAllBytes(Paths.get("./Hello.xlass"));
            for (int i=0;i<bytes.length; i++) {
                bytes[i] = (byte)(255-bytes[i]);
            }

            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
            return new byte[]{1};
        }
    }
}